<?php
/**
 * 后台微信交互设置控制器
 */
namespace Admin\Controller;
use Common\Common;
class WechatController extends CommonController
{
    /**
     * 后台公众号首页
     */
    function index()
    {
        $userinfo=session('sys_user_info');
        $this->assign('userinfo',$userinfo);
        $wechats=M('wechat_bindwechat')->select();
        $this->account_info=$wechats[0];
        $menus=M('sys_menu')->where(array('parent_id'=>0))->order('sort_num asc')->select();//一级菜单
        $this->assign('menus',$menus);
        $type=M('user_type')->where(array('user_type_id'=>$userinfo['user_type_id']))->find();//用户角色
        $this->assign('type',$type);
        $this->display();
    }

    /**
     * 帐户信息
     */
    function center()
    {
        $wechats=M('wechat_bindwechat')->select();
        $this->wechat=$wechats[0];
        $this->display();
    }

    /**
     * 文本素材列表
     */
    function replytext(){
        $this->get_contents('text');
        $this->display();
    }

    /**
     * 编辑文本素材
     */
    function edittext(){
        $action=I('action');
        $this->assign('action',$action);
        if(IS_POST){
            $arrmsg=array('errno'=>0,'error'=>'','url'=>'');
            $dt['content']=I('content');
            $action=I('action');
            if($action=='add'){
                $id=create_guid();
                $dt['contentid']=$id;
                $dt['contenttype']='text';
                $dt['addtime']=date('Y-m-d H:i:s',time());
                $row=M('wechat_contents')->add($dt);//添加数据
                if(!$row){
                    $arrmsg['errno']=1;
                    $arrmsg['error']='数据插入失败，请重新尝试';
                    $this->ajaxReturn($arrmsg);
                }
            }else{
                $dt['contentid']=I('cid');
                M('wechat_contents')->save($dt);//修改数据
            }
            $arrmsg['error']='文本编辑成功！';
            $arrmsg['url']=U('Admin/Wechat/replytext');
            $this->ajaxReturn($arrmsg);
        }else{
            if($action=='edit'){
                $map['contentid']=I('cid');
                $wechats=M('wechat_contents')->where($map)->select();
                if(count($wechats)>0){
                    $this->contents=$wechats[0];
                }
            }
            $this->display();
        }
    }

    /**
     * 删除文本素材
     */
    function deltext(){
        $map['contentid']=I('cid');
        $map['contenttype']='text';
        $row=M('wechat_contents')->where($map)->delete();
        if(!$row){
            echo '数据删除失败，请重新尝试';
        }
        redirect(U('Admin/Wechat/replytext'));
    }

    /**
     * 图文素材列表
     */
    function replynews(){
        $this->get_contents('news');
        $this->display();
    }

    /**
     * 获取素材
     */
    function get_contents($type){
        $map['contenttype']=$type;
        $con=M('wechat_contents');
        $count = $con->where($map)->count();// 查询满足要求的总记录数
        $Page = new Common\Page($count, 8);// 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page->show();// 分页显示输出
        $this->assign('page', $show);// 赋值分页输出
        $this->assign('total', $count);// 总数
        $this->assign('nowPage', $Page->nowPage);// 当前页数
        $this->assign('totalPages', $Page->totalPages);// 分页总页面数
        $this->contents=$con->where($map)->order("addtime desc")->limit($Page->firstRow . ',' . $Page->listRows)->select();
    }

    /**
     * 编辑单图文
     */
    function editnew(){
        $action=I('action');
        $this->assign('action',$action);
        if(IS_POST){
            $arrmsg=array('errno'=>0,'error'=>'','url'=>'');

            $arr=I('new');//新加
            $action=I('action');
            if($arr){
                $data_add=array();
                if($action=='add'){
                    $cid=create_guid();
                }
                else{
                    $cid=I('cid');
                    $map['contentid']=$cid;
                    $row=M('wechat_contents_detail')->where($map)->delete();
                    if(!$row){
                        $arrmsg['errno']=1;
                        $arrmsg['error']='数据删除失败，请重新尝试';
                        $this->ajaxReturn($arrmsg);
                    }
                }
                $datetime=date('Y-m-d H:i:s',time());
                foreach($arr['sortnum'] as $k=>$v)
                {
                    $udata=array();
                    $udata['detailid']=create_guid();
                    $udata['contentid']=$cid;
                    $udata['detailtitle']=$arr['detailtitle'][$k];
                    $udata['sortnum']=$arr['sortnum'][$k];
                    $udata['detaillogo']=$arr['detaillogo'][$k];
                    $udata['detailintro']=$arr['detailintro'][$k];
                    $udata['detailcontent']=$arr['detailcontent'][$k];
                    $udata['detaillink']=$arr['detaillink'][$k];
                    $udata['addtime']=$datetime;
                    array_push($data_add,$udata);
                    $row=M('wechat_contents_detail')->add($udata);//添加数据
                    if(!$row){
                        $arrmsg['errno']=1;
                        $arrmsg['error']='数据插入失败，请重新尝试';
                        $this->ajaxReturn($arrmsg);
                    }
                }
                if($action=='add'){
                    $dt['contentid']=$cid;
                    $dt['contenttype']='news';
                    $dt['content']=json_encode($data_add);
                    $dt['addtime']=$datetime;
                    $row=M('wechat_contents')->add($dt);//添加数据
                    if(!$row){
                        $arrmsg['errno']=1;
                        $arrmsg['error']='数据插入失败，请重新尝试';
                        $this->ajaxReturn($arrmsg);
                    }
                }else{
                    $dt['contentid']=$cid;
                    $dt['content']=json_encode($data_add);
                    M('wechat_contents')->save($dt);//修改数据
                }
            }
            $arrmsg['error']='素材编辑成功！';
            $arrmsg['url']=U('Admin/Wechat/replynews');
            $this->ajaxReturn($arrmsg);
        }else{
            if($action=='edit'){
                $map['contentid']=I('cid');
                $this->assign('cid',$map['contentid']);
                $wechats=M('wechat_contents_detail')->where($map)->select();
                if(count($wechats)>0){
                    $this->contents=$wechats[0];
                    $this->count=count($wechats);
                }
            }
            $this->display();
        }
    }

    /**
     * 编辑多图文
     */
    function editnews(){
        $action=I('action');
        $this->assign('action',$action);

        if($action=='edit'){
            $map['contentid']=I('cid');
            $this->assign('cid',$map['contentid']);
            $wechats=M('wechat_contents_detail')->where($map)->order("sortnum asc")->select();
            if(count($wechats)>0){
                $this->list=$wechats;
                $infos=M('wechat_contents')->where($map)->select();
                $this->info=$infos[0];
                $this->count=count($wechats);
            }
        }
        $this->display();
    }

    /**
     * 删除图文
     */
    function delnews(){
        $cid=I('cid');
        $map['contentid']=$cid;
        $row=M('wechat_contents')->where($map)->delete();
        if(!$row){
            echo '数据删除失败，请重新尝试';
        }
        $row=M('wechat_contents_detail')->where($map)->delete();
        if(!$row){
            echo '数据删除失败，请重新尝试';
        }
        redirect(U('Admin/Wechat/replynews'));
    }

    /**
     * 关注时回复type=first
     * 默认回复type=default
     */
    function replysubscribe(){
        if(IS_POST){

        }else{
            $type=I('rtype','first');
            $this->rtype=$type;
            $map['replytype']=$type;
            $reply = D("Wechatreply")->relation(true)->where($map)->select();
            $this->count=count($reply);
            if($this->count>0){
                $this->info=$reply[0];
            }
            $this->display();
        }
    }

    /**
     * ajax获取素材列表
     */
    function selcontent(){
        $map['contenttype']=I('get.type');
        $con=M('wechat_contents');
        $count = $con->where($map)->count();// 查询满足要求的总记录数
        $Page = new Common\Page($count, 8);// 实例化分页类 传入总记录数和每页显示的记录数
        $contents=$con->where($map)->order("addtime desc")->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $arr['totlecount']=count($contents);
        $arr['list']=$contents;
        $this->ajaxReturn($arr);
    }

    /**
     * 设置素材(首次关注first，默认回复default)
     */
    function setcontent(){
        $arrmsg=array('errno'=>0,'error'=>'','url'=>'');
        $type=I('type');//回复类型
        $cid=I('cid');
        $map['replytype']=$type;
        $reply=M('wechat_reply')->where($map)->select();
        $map['contentid']=$cid;
        if(count($reply)>0){
            $map['replyid']=$reply[0]['replyid'];
            $row=M('wechat_reply')->save($map);//修改数据
            if(!$row){
                $arrmsg['errno']=1;
                $arrmsg['error']='数据编辑失败，请重新尝试';
                $this->ajaxReturn($arrmsg);
            }
        }else{
            $map['replyid']=create_guid();
            $map['addtime']=date('Y-m-d H:i:s',time());
            $row=M('wechat_reply')->add($map);//添加数据
            if(!$row){
                $arrmsg['errno']=1;
                $arrmsg['error']='数据插入失败，请重新尝试';
                $this->ajaxReturn($arrmsg);
            }
        }
        if($type=='first'){
            $arrmsg['error']='关注时回复内容设置成功';
        }else{
            $arrmsg['error']='默认回复内容设置成功';
        }
        $arrmsg['url']=U('Admin/Wechat/replysubscribe').'?rtype='.$type;
        $this->ajaxReturn($arrmsg);
    }

    /**
     * 关键词回复列表
     */
    function replykeyword(){
        if(IS_POST){

        }else{
            $map['replytype']='textkey';
            $con=D('Wechatreply');
            $count = $con->relation(true)->where($map)->count();// 查询满足要求的总记录数
            $Page = new Common\Page($count, 10);// 实例化分页类 传入总记录数和每页显示的记录数
            $show = $Page->show();// 分页显示输出
            $this->assign('page', $show);// 赋值分页输出
            $this->assign('total', $count);// 总数
            $this->assign('nowPage', $Page->nowPage);// 当前页数
            $this->assign('totalPages', $Page->totalPages);// 分页总页面数
            $this->contents=$con->relation(true)->where($map)->order("addtime desc")->limit($Page->firstRow . ',' . $Page->listRows)->select();
            $this->display();
        }
    }

    /**
     * 编辑关键词
     */
    function editkeyword(){
        $action=I('get.action','add');
        $this->action=$action;
        if(IS_POST){
            $arrmsg=array('errno'=>0,'error'=>'','url'=>'');
            $dt['keyname']=I('keyname');
            $dt['contentid']=I('cid');
            $action=I('action');
            if($action=='add'){
                $dt['replyid']=create_guid();
                $dt['addtime']=date('Y-m-d H:i:s',time());
                $dt['replytype']='textkey';
                $row=M('wechat_reply')->add($dt);
                if(!$row){
                    $arrmsg['errno']=1;
                    $arrmsg['error']='数据插入失败，请重新尝试';
                    $this->ajaxReturn($arrmsg);
                }
            }else{
                $dt['replyid']=I('rid');
                $row=M('wechat_reply')->save($dt);
                if(!$row){
                    $arrmsg['errno']=1;
                    $arrmsg['error']='数据编辑失败，请重新尝试';
                    $this->ajaxReturn($arrmsg);
                }
            }
            $arrmsg['error']='关键词编辑成功！';
            $arrmsg['url']=U('Admin/Wechat/replykeyword');
            $this->ajaxReturn($arrmsg);
        }else{
            if($action=='edit'){
                $rid=I('rid');
                $this->rid=$rid;
                $map['replyid']=$rid;
                $re=D('Wechatreply')->relation(true)->where($map)->select();
                $this->info=$re[0];
            }
            $this->display();
        }
    }

    /**
     *ajax 获取素材
     */
    function getcontent(){
        $map['contentid']=I('cid');
        $re=M('wechat_contents')->where($map)->select();
        $arr=$re[0];
        $this->ajaxReturn($arr);
    }

    /**
     *ajax 删除关键词
     */
    function delreply(){
        if(IS_POST){
            //回复内容
            $arrmsg=array('errno'=>0,'error'=>'','url'=>'');
            $ids=I('ids');
            for($i=0;$i<count($ids);$i++){
                $map['replyid']=$ids[$i];
                $row=M('wechat_reply')->where($map)->delete();
                if(!$row){
                    $arrmsg['errno']=1;
                    $arrmsg['error']='数据删除失败，请重新尝试';
                    $this->ajaxReturn($arrmsg);
                    break;
                }
            }
            $this->ajaxReturn($arrmsg);
        }
    }

    /**
     * 菜单授权设置
     */
    function menuset(){
        if(IS_POST){
            //回复内容
            //成功 $arrmsg=array('errno'=>0,'error'=>'提示信息','url'=>'空时不跳转');'tip'=>'提示信息，中间显示',
            $arrmsg=array('errno'=>1,'tip'=>'','url'=>'');
            $dt=I('post.');
            M('wechat_bindwechat')->save($dt);
            $arrmsg['errno']=0;
            $arrmsg['error']='授权设置成功！';
            $this->ajaxReturn($arrmsg);
        }else{
            $re=M('wechat_bindwechat')->select();
            $this->info=$re[0];
            $this->display();
        }
    }

    /**
     * 菜单设置
     */
    function menu(){
        if(IS_POST){
            $arrmsg=array('errno'=>1,'tip'=>'','url'=>'');
            $arr=I('new');//新加
            $arr_edit=I('ps');//修改
            //新加菜单
            if($arr){
                foreach($arr['sort'] as $k=>$v)
                {
                    $udata=array();
                    $udata['menuid']=create_guid();
                    $udata['sortnum']=$arr['sort'][$k];
                    $udata['menuname']=$arr['name'][$k];
                    $is_url=$arr['is_url'][$k];
                    if($is_url==1){
                        $udata['menutype']='click';
                        $udata['menukey']=$arr['key'][$k];
                        $udata['menuurl']='';
                    }else if($is_url==2){
                        $udata['menutype']='view';
                        $udata['menukey']='';
                        $udata['menuurl']=$arr['key'][$k];
                    }
                    $udata['parentmenuid']=$arr['parent_id'][$k];
                    $udata['isshow']=isset($arr['is_show'][$k])?$arr['is_show'][$k]:'0';//1显示,0不显示
                    $udata['contentid']='';
                    $udata['addtime']=date('Y-m-d H:i:s',time());
                    M('wechat_menu')->add($udata);//添加
                }
            }
            //修改菜单
            if($arr_edit){
                foreach($arr_edit as $k=>$v){
                    $udata=array();
                    $udata['menuid']=$k;
                    $udata['sortnum']=$arr_edit[$k]['sort'];
                    $udata['menuname']=$arr_edit[$k]['name'];
                    $is_url=$arr_edit[$k]['is_url'];
                    if($is_url==1){
                        $udata['menutype']='click';
                        $udata['menukey']=$arr_edit[$k]['key'];
                        $udata['menuurl']='';
                    }else if($is_url==2){
                        $udata['menutype']='view';
                        $udata['menukey']='';
                        $udata['menuurl']=$arr_edit[$k]['key'];
                    }
                    $udata['parentmenuid']=$arr_edit[$k]['parent_id'];
                    $udata['isshow']=isset($arr_edit[$k]['is_show'])?$arr_edit[$k]['is_show']:'0';//1显示,0不显示
                    $udata['contentid']='';
                    M('wechat_menu')->save($udata);
                }
            }
            $arrmsg['errno']=0;
            $arrmsg['error']='自定义菜单编辑成功！';
            $arrmsg['url']=U('Admin/Wechat/menu');
            $this->ajaxReturn($arrmsg);
        }else{
            //加载菜单
            $menulist=M('wechat_menu')->select();
            $this->menulist=$menulist;
            $this->mainmenu=get_mainmenu($menulist,'0');
            $this->display();
        }
    }

    /**
     * 删除菜单
     */
    function delmenu(){
        $map['menuid']=I('menuid');
        M('wechat_menu')->where($map)->delete();
        redirect(U('Admin/Wechat/menu'));
    }

    /**
     * 生成菜单
     */
    function createmenu(){
        //回复内容
        //成功 $arrmsg=array('errno'=>0,'error'=>'提示信息','url'=>'空时不跳转');'tip'=>'提示信息，中间显示',
        $arrmsg=array('errno'=>0,'error'=>'','url'=>'');
        $wechat=M('wechat_bindwechat')->select();
        $appid=$wechat[0]['appid'];
        $appsecret=$wechat[0]['appsecret'];
        if($appid==''||$appsecret==''){
            $arrmsg['error']='应用ID或应用密钥为空';
            $this->ajaxReturn($arrmsg);
        }
        $weixin = new Common\WeixinCommon();
        $access_token=$weixin->getAccessToken($appid,$appsecret);
        if($access_token){
            //取得菜单参数
            $menudata=$this->_get_usable_menu();
            //生成菜单
            if(is_array($menudata)){
                $re=$weixin->createMenu($access_token,urldecode(json_encode($menudata)));
                if($re){
                    $arrmsg['error']='生成菜单成功!';
                }else{
                    $arrmsg['error']='生成菜单失败!';
                }
            }else{
                $arrmsg['error']='生成菜单失败~';
            }
        }else{
            $arrmsg['error']='应用ID或应用密钥错误，ACCESS_TOKEN获取失败';
        }
        $this->ajaxReturn($arrmsg);
    }

    /**
     * 取得可用菜单并组合成data
     */
    private function _get_usable_menu(){
        $map['isshow']='1';
        $menulist=M('wechat_menu')->where($map)->select();
        //返回菜单
        $arr_mainmenu=array();
        //主菜单
        $mainmenu=get_mainmenu($menulist,'0');

        if(count($mainmenu)<1||count($mainmenu)>3)
        {
            return '主菜单数量为1个至3个，请重新分配';
        }
        foreach($mainmenu as $item){
            $item_mainmenu=array();
            //子菜单
            $submenu=get_mainmenu($menulist,$item['menuid']);

            //有子菜单
            if(count($submenu)>0){
                $item_mainmenu['name']=urlencode($item['menuname']);
                if(count($submenu)<1||count($submenu)>5)
                {
                    return '二级菜单数量为1个至5个，请重新分配';
                }
                $item_submenu=array();
                foreach($submenu as $subitem){
                    $arr_sub=array();
                    $arr_sub['type']=$subitem['menutype'];
                    $arr_sub['name']=urlencode($subitem['menuname']);
                    if($subitem['menutype']=='click'){
                        $arr_sub['key']=$subitem['menukey'];
                    }else if($subitem['menutype']=='view'){
                        $arr_sub['url']=urlencode($subitem['menuurl']);
                    }
                    array_push($item_submenu,$arr_sub);
                }
                $item_mainmenu['sub_button']=$item_submenu;
            }else{
                $item_mainmenu['type']=$item['menutype'];
                $item_mainmenu['name']=urlencode($item['menuname']);
                if($item['menutype']=='click'){
                    $item_mainmenu['key']=$item['menukey'];
                }else if($item['menutype']=='view'){
                    $item_mainmenu['url']=urlencode($item['menuurl']);
                }
            }
            array_push($arr_mainmenu,$item_mainmenu);
        }
        $re['button']=$arr_mainmenu;
        return $re;
    }

    /**
     * 粉丝管理（微信公众号关注用户列表）
     */
    function wxusers(){
        $user=M('wx_users');
        $keyword=I('keyword','');
        $this->assign('keyword',$keyword);
        if($keyword!=''){
            $map['nickname']=array('like',"%$keyword%");
        }
        $count = $user->count();// 查询满足要求的总记录数
        $Page = new Common\Page($count, 10);// 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page->show();// 分页显示输出
        $this->assign('page', $show);// 赋值分页输出
        $this->assign('total', $count);// 总数
        $this->assign('nowPage', $Page->nowPage);// 当前页数
        $this->assign('totalPages', $Page->totalPages);// 分页总页面数
        $this->users=$user->where($map)->order("subscribe_time desc")->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $this->groups=M('wx_group')->select();
        $this->display();
    }

    /**
     * 分组管理
     */
    function groups(){
        $table=D('Wxgroup');
        $keyword=I('keyword','');
        $this->assign('keyword',$keyword);
        if($keyword!=''){
            $map['groupname']=array('like',"%$keyword%");
        }
        $count = $table->relation(true)->where($map)->count();// 查询满足要求的总记录数
        $Page = new Common\Page($count, 10);// 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page->show();// 分页显示输出
        $this->assign('page', $show);// 赋值分页输出
        $this->assign('total', $count);// 总数
        $this->assign('nowPage', $Page->nowPage);// 当前页数
        $this->assign('totalPages', $Page->totalPages);// 分页总页面数
        $this->groups=$table->relation(true)->where($map)->order("add_time desc")->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $this->display();
    }

    /**
     * 编辑分组
     */
    function group_edit(){
        if(IS_POST){
            $arrmsg=array('errno'=>1,'error'=>'','url'=>'');
            $action=I('action');
            $dt['groupname']=I('groupname');
            if($action=='add'){
                $dt['add_time']=time();
                $row=M('wx_group')->add($dt);
                if(!$row){
                    $arrmsg['error']='网络异常，请重新尝试';
                    $this->ajaxReturn($arrmsg);
                }
            }else{
                $dt['id']=I('id');
                $row=M('wx_group')->save($dt);
                if(!$row){
                    $arrmsg['error']='网络异常，请重新尝试';
                    $this->ajaxReturn($arrmsg);
                }
            }
            $arrmsg['errno']=0;
            $arrmsg['error']='分组编辑成功！';
            $arrmsg['url']=U('Admin/Wechat/groups');
            $this->ajaxReturn($arrmsg);
        }else{
            $action=I('action');
            $this->assign('action',$action);
            if($action=='edit'){
                $map['id']=I('id');
                $this->info=M('wx_group')->where($map)->find();
            }
            $this->display();
        }
    }

    /**
     * 删除分组
     */
    function del_group(){
        //回复内容
        $arrmsg=array('errno'=>0,'error'=>'','url'=>'');
        $ids=I('ids');
        for($i=0;$i<count($ids);$i++){
            $map['id']=$ids[$i];
            $row=M('wx_group')->where($map)->delete();
            if(!$row){
                $arrmsg['errno']=1;
                $arrmsg['error']='数据删除失败，请重新尝试';
                $this->ajaxReturn($arrmsg);
                break;
            }
        }
        $this->ajaxReturn($arrmsg);
    }

    /**
     * 用户分组
     */
    function set_user_group(){
        if(IS_POST){
            $arrmsg=array('errno'=>1,'error'=>'','url'=>'');
            $openids=I('openids');
            $dt['group_id']=I('group_id');
            for($i=0;$i<count($openids);$i++){
                $dt['openid']=$openids[$i];
                $count=M('wx_user_group')->where($dt)->count();
                if($count<=0){
                    $row=M('wx_user_group')->add($dt);
                    if(!$row){
                        $arrmsg['error']="网络异常，请重新尝试";
                        $this->ajaxReturn($arrmsg);
                        break;
                    }
                }
            }
            $arrmsg['errno']=0;
            $arrmsg['error']="加入分组成功";
            $this->ajaxReturn($arrmsg);
        }
    }

    /**
     * 分组用户列表
     */
    function userlist(){
        $table=D('Groupusers');
        $map['id']=I('group_id');
        $users=$table->relation(true)->where($map)->find();
        $this->group_id=$users['id'];
        $this->groupname=$users['groupname'];
        $this->users=$users['wx_users'];
        $this->display();
    }

    /**
     * 删除分组用户
     */
    function del_gp_user(){
        //回复内容
        $arrmsg=array('errno'=>0,'error'=>'','url'=>'');
        $map['group_id']=I('group_id');
        $ids=I('ids');
        for($i=0;$i<count($ids);$i++){
            $map['openid']=$ids[$i];
//            dump($map);
            $row=M('wx_user_group')->where($map)->delete();
            if(!$row){
                $arrmsg['errno']=1;
                $arrmsg['error']='数据删除失败，请重新尝试';
                $this->ajaxReturn($arrmsg);
                break;
            }
        }
        $this->ajaxReturn($arrmsg);
    }

    /**
     * 群发功能
     */
    function sendmsg(){
        $this->groups=M('wx_group')->select();
        $this->display();
    }

    /**
     * 业主管理
     */
    function owners(){
        $where=" where 1=1 ";
        $keyword=I('keyword','');
        $this->assign('keyword',$keyword);
        if($keyword!=''){
            $where.=" and ( u.uname like '%$keyword%' or phone like '%$keyword%' or idcard like '%$keyword%' )";
        }
        $page_num=20;//每页条数
        $page=I('p',1);
        $nownums=($page-1)*$page_num;
        $user=M()->query("select count(u.id) as count from exp_wx_users u,exp_cqlf_homes h $where and u.id=h.user_id");
        $count = $user[0]['count'];// 查询满足要求的总记录数
        $Page = new Common\Page($count, $page_num);// 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page->show();// 分页显示输出
        $this->assign('page', $show);// 赋值分页输出
        $this->assign('total', $count);// 总数
        $this->assign('nowPage', $Page->nowPage);// 当前页数
        $this->assign('totalPages', $Page->totalPages);// 分页总页面数
        $this->users=M()->query("select u.*,h.buname,h.bldfullname,h.room from exp_wx_users u,exp_cqlf_homes h $where and u.id=h.user_id limit $nownums,$page_num");
//        dump($count);
//        dump($this->users);
        $this->display();
    }

    /**
     * 高级群发推送业主消息
     */
    function owners_sendmsg(){
        $keyword=I('keyword','');
        $pro=I('pro','');
        $pro_name=I('pro_name','');
        $this->assign("keyword",$keyword);
        $this->assign("pro",$pro);
        $this->assign("pro_name",$pro_name);

        $where=" where 1=1 ";
        if(!empty($keyword)){
            $where.=" and ( u.uname like '%$keyword%' or phone like '%$keyword%' or idcard like '%$keyword%' )";
        }
        if(!empty($pro)){
            $where.=" and h.bldfullname like '%$pro%'";
        }
        if(!empty($pro_name)){
            $where.=" and h.bldfullname like '%$pro_name%'";
        }
        $page_num=50;//每页条数
        $page=I('p',1);
        $nownums=($page-1)*$page_num;
        $user=M()->query("select count(u.id) as count from exp_wx_users u,exp_cqlf_homes h $where and u.id=h.user_id");
        $count = $user[0]['count'];// 查询满足要求的总记录数
        $Page = new Common\Page($count, $page_num);// 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page->show();// 分页显示输出
        $this->assign('page', $show);// 赋值分页输出
        $this->assign('total', $count);// 总数
        $this->assign('nowPage', $Page->nowPage);// 当前页数
        $this->assign('totalPages', $Page->totalPages);// 分页总页面数
        $this->users=M()->query("select u.*,h.buname,h.bldfullname,h.room from exp_wx_users u,exp_cqlf_homes h $where and u.id=h.user_id limit $nownums,$page_num");
//        dump(M()->GetLastSql());

        $pros=M('cqlf_pros')->field('pro_name')->select();
        $pros=unique_arr($pros,true);
        $this->assign("pros",$pros);
        $this->display();
    }

    /**
     * 高级群发
     */
    function msg_send(){
        $wechat=M('wechat_bindwechat')->select();
        $appid=$wechat[0]['appid'];
        $appsecret=$wechat[0]['appsecret'];
        $weixin = new Common\WeixinCommon();
        $access_token=$weixin->getAccessToken($appid,$appsecret);
        if(!$access_token){
            echo 'access_token获取失败';
            return;
        }

        $openids=I('openids');
        $user=array();
        if(count($openids)>0){
            if($openids[0]=='0'){//全选
                $keyword=I('keyword','');
                $pro=I('pro','');
                $pro_name=I('pro_name','');
                $where=" where 1=1 ";
                if(!empty($keyword)){
                    $where.=" and ( u.uname like '%$keyword%' or phone like '%$keyword%' or idcard like '%$keyword%' )";
                }
                if(!empty($pro)){
                    $where.=" and h.bldfullname like '%$pro%'";
                }
                if(!empty($pro_name)){
                    $where.=" and h.bldfullname like '%$pro_name%'";
                }
                $sendusers=M()->query("select u.*,h.buname,h.bldfullname,h.room from exp_wx_users u,exp_cqlf_homes h $where and u.id=h.user_id");
                if(count($sendusers)>0){
                    foreach($sendusers as $item){
                        $user[]=$item['openid'];
                    }
                }
            }else{
                for($i=0;$i<count($openids);$i++){
                    $user[]=$openids[$i];
                }
            }
        }
        $news['touser']=$user;

        $msgtype=I('msgtype');//群发类型
        switch($msgtype){
            //文本
            case 'text':
                $news['text']=array('content'=>urlencode(I('content')));
                break;
            //图片
            case 'image':
                $mediapath=I('upimg');
                $mediapath=str_replace('//','/',$mediapath);
                $mediapath=str_replace('/','\\',$mediapath);
                $mediapath=dirname(__FILE__).'\..\..\..\..'.$mediapath;
                $media_id=$weixin->getThumbMediaId($access_token,$mediapath,'image');
                if(!$media_id){
                    echo '获取多媒体图片id失败';
                    return;
                }
                $news['image']=array('media_id'=>$media_id);
                break;
            //图文
            case 'mpnews':
                $contentid=I('contentid');//素材编号
                $mp['contentid']=$contentid;
                $list=M('wechat_contents_detail')->where($mp)->order("sortnum asc")->select();
                $item_con=array();
                foreach($list as $item){
                    $arr_sub=array();
                    $mediapath=str_replace('/','\\',$item['detaillogo']);
                    $mediapath=dirname(__FILE__).'\..\..\..\..'.$mediapath;
                    $media_id=$weixin->getThumbMediaId($access_token,$mediapath,'image');
                    if(!$media_id){
                        echo '获取多媒体图片id失败';
                        return;
                    }
                    $arr_sub['thumb_media_id']=$media_id;
                    $arr_sub['author']="";
                    $arr_sub['title']=urlencode($item['detailtitle']);
                    $arr_sub['content_source_url']=urlencode($item['detaillink']);
                    $content=htmlspecialchars_decode($item['detailcontent']);
                    $content=str_replace("/cqlfgroup","http://".$_SERVER['HTTP_HOST']."/cqlfgroup",$content);
                    $arr_sub['content']=replay_china($content);
                    $arr_sub['digest']="";
                    $arr_sub['show_cover_pic']="0";
                    $item_con[]=$arr_sub;
                }
                $articlesdata['articles']=$item_con;//图文素材数据
                $articlesdata=urldecode(json_encode($articlesdata));
                $media_id=$weixin->getMediaId($access_token,$articlesdata);
                if(!$media_id){
                    echo '获取图文素材id失败';
                    return;
                }
                $news['mpnews']=array('media_id'=>$media_id);
                break;
            //语音
            case 'voice':
                $mediapath="C:\Users\Administrator\Desktop\lyg.mp3";
                $media_id=$weixin->getThumbMediaId($access_token,$mediapath,'voice');
                if(!$media_id){
                    echo '获取多媒体语音id失败';
                    return;
                }
                $news['voice']=array('media_id'=>$media_id);
                break;
            //视频
            case 'mpvideo':
                $mediapath="C:\Users\Administrator\Desktop\lyg.mp4";
                $media_id=$weixin->getThumbMediaId($access_token,$mediapath,'video');
                if(!$media_id){
                    echo '获取多媒体视频id失败';
                    return;
                }
                $video['media_id']=$media_id;
                $video['title']='第一个视频';
                $video['description']='这里是视频的描述';
                $media_id=$weixin->getVideoMediaId($access_token,json_encode($video));
                if(!$media_id){
                    echo '获取视频id失败';
                    return;
                }
                $news['mpvideo']=array('media_id'=>$media_id);
                break;
        }
//        return;
        $news['msgtype']=$msgtype;
        $news=urldecode(json_encode($news));
        $re=$weixin->sendMsg($access_token,$news);//根据openid群发
        if(!$re){
            $msg['errno']=0;
            $this->ajaxReturn($msg);
        }
        $msg=array('errno'=>1,'msg'=>'发送成功');
        $this->ajaxReturn($msg);
    }

    /**
     * 发送客服消息
     */
    function custom_send(){
        $wechat=M('wechat_bindwechat')->select();
        $appid=$wechat[0]['appid'];
        $appsecret=$wechat[0]['appsecret'];
        $weixin = new Common\WeixinCommon();
        $access_token=$weixin->getAccessToken($appid,$appsecret);
        if(!$access_token){
            echo 'access_token获取失败';
            return;
        }
        $msgtype=I('msgtype');//群发类型
        $msg['msgtype']=$msgtype;
        switch($msgtype){
            //文本
            case "text":
                $con['content']=urlencode(I('content'));//发送的文本内容
                $msg['text']=$con;
                break;
            //图片
            case "image":
                $mediapath=I('upimg');
                $mediapath=str_replace('/','\\',$mediapath);
                $mediapath=dirname(__FILE__).'\..\..\..\..'.$mediapath;
                $media_id=$weixin->getThumbMediaId($access_token,$mediapath,'image');
                if(!$media_id){
                    echo '获取多媒体图片id失败';
                    return;
                }
                $con['media_id']=$media_id;
                $msg['image']=$con;
                break;
            //图文
            case "news":
                $contentid=I('contentid');//素材编号
                $mp['contentid']=$contentid;
                $list=M('wechat_contents_detail')->where($mp)->order("sortnum asc")->select();
                $item_con=array();
                foreach($list as $item){
                    $arr_sub=array();
                    $arr_sub['title']=urlencode($item['detailtitle']);
                    $arr_sub['description']=urlencode($item['detailtitle']);
                    $arr_sub['url']=urlencode($item['detaillink']);
                    $arr_sub['picurl']='http://'.$_SERVER['HTTP_HOST'].$item['detaillogo'];
                    $item_con[]=$arr_sub;
                }
                $con['articles']=$item_con;//图文素材数据
                $msg['news']=$con;
                break;
            //语音
            case "voice":
                $mediapath="C:\Users\Administrator\Desktop\hudong.mp3";
                $media_id=$weixin->getThumbMediaId($access_token,$mediapath,'voice');
                if(!$media_id){
                    echo '获取多媒体图片id失败';
                    return;
                }
                $con['media_id']=$media_id;
                $msg['voice']=$con;
                break;
            //视频
            case "video":
                $mediapath="C:\Users\Administrator\Desktop\hudong.mp4";
                $media_id=$weixin->getThumbMediaId($access_token,$mediapath,'video');
                if(!$media_id){
                    echo '获取多媒体图片id失败';
                    return;
                }
                $con['media_id']=$media_id;
                $con['title']="";//音乐标题
                $con['description']="";//视频消息的描述
                $msg['video']=$con;
                break;
            //音乐
            case "music":
                $mediapath="C:\Users\Administrator\Desktop\hudong.jpg";
                $media_id=$weixin->getThumbMediaId($access_token,$mediapath,'thumb');
                if(!$media_id){
                    echo '获取多媒体图片id失败';
                    return;
                }
                $con['title']="";//视频消息的标题
                $con['description']="";//音乐描述
                $con['musicurl']="";//音乐链接
                $con['hqmusicurl']="";//高品质音乐链接，wifi环境优先使用该链接播放音乐
                $con['thumb_media_id']=$media_id;//缩略图的媒体ID
                $msg['music']=$con;
                break;
        }

        $openids=I('openids');
        $user=array();
        if(count($openids)>0){
            if($openids[0]=='0'){//全选
                $keyword=I('keyword','');
                $pro=I('pro','');
                $pro_name=I('pro_name','');
                $where=" where 1=1 ";
                if(!empty($keyword)){
                    $where.=" and ( u.uname like '%$keyword%' or phone like '%$keyword%' or idcard like '%$keyword%' )";
                }
                if(!empty($pro)){
                    $where.=" and h.bldfullname like '%$pro%'";
                }
                if(!empty($pro_name)){
                    $where.=" and h.bldfullname like '%$pro_name%'";
                }
                $sendusers=M()->query("select u.openid from exp_wx_users u,exp_cqlf_homes h $where and u.id=h.user_id");
                if(count($sendusers)>0){
                    foreach($sendusers as $item){
                        $msg['touser'] = $item['openid'];
                        $sendmsg = urldecode(json_encode($msg));
                        $send = $weixin->sendCustom($access_token, $sendmsg);
                        if(!$send){
                            echo '发送失败';
                            return;
                        }
                    }
                }
            }else{
                for($i=0;$i<count($openids);$i++){
                    $msg['touser'] = $openids[$i];
                    $sendmsg = urldecode(json_encode($msg));
                    $send = $weixin->sendCustom($access_token, $sendmsg);
                    if(!$send){
                        echo '发送失败';
                        return;
                    }
                }
            }
        }
        $msg=array('errno'=>1,'msg'=>'发送成功');
        $this->ajaxReturn($msg);
    }
}